using System.Net;
using System.Text;

namespace muduoDotNet.Examples
{
    public class EchoServerExample
    {
        public static void RunExample()
        {
            Main(new string[0]);
        }
        
        static void Main(string[] args)
        {
            Logger.Info("Echo Server Started");
            
            // 创建事件循环
            var loop = new EventLoop();
            
            // 创建TCP服务器
            var server = new TcpServer(loop, new IPEndPoint(IPAddress.Any, 9999));
            
            // 设置连接回调
            server.ConnectionCallback = (conn) =>
            {
                Logger.Info($"Connection {conn.Name} established");
            };
            
            // 设置消息回调
            server.MessageCallback = (conn, buffer) =>
            {
                // 读取消息
                string message = Encoding.UTF8.GetString(buffer.ReadAll());
                
                Logger.Info($"Received: {message}");
                
                // 发送消息回客户端
                conn.Send(Encoding.UTF8.GetBytes($"Echo: {message}"));
            };
            
            // 设置写完成回调
            server.WriteCompleteCallback = (conn) =>
            {
                Logger.Info($"Write complete for {conn.Name}");
            };
            
            // 启动服务器
            server.Start();
            
            Logger.Info("Server is listening on port 9999");
            Logger.Info("Press Enter to stop the server");
            
            // 运行事件循环
            Task.Run(() =>
            {
                loop.Start();
            });
            
            // 等待用户输入以停止服务器
            Console.ReadLine();
            
            // 停止服务器
            loop.Stop();
            server.Dispose();
            loop.Dispose();
            
            Logger.Info("Echo Server Stopped");
        }
    }
}